﻿using EasyBuyShop.DAL;
using EasyBuyShop.Models;
using Microsoft.AspNetCore.Mvc;

namespace EasyBuyShop.Controllers
{
    public class PurchaseController : Controller
    {
        public IActionResult Index()
        {
            var username = HttpContext.Session.GetString("username");
            var realName = HttpContext.Session.GetString("realname");
            var userId = HttpContext.Session.GetInt32("userid");
            ViewData["Username"] = username;
            ViewData["RealName"] = realName;
            var purchaseDal = new PurchaseDal();
            var purchases =  purchaseDal.GetPurchases(userId.Value);
            var products=new List<Product>();
            var shops = new List<Shop>();
            if (purchases != null && purchases.Count() > 0)
            {
                var productDal = new ProductDal();
                var pIds = purchases.Select(x => x.ProductId).ToList();
                products = productDal.GetProductListByIds(pIds);
                if (products != null && products.Count() > 0)
                {
                    var shopDal = new ShopDal();
                    shops = shopDal.GetShops(products.Select(r => r.ShopId).ToList());
                }
            }

            ViewData["Shops"] = shops;
            ViewData["ProductList"] = products;
            ViewData["Purchases"] = purchases;
            return View();
        }

        /// <summary>
        /// 首页或商品列表快捷下单
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Buy(int productId)
        {
            Msg msg = new Msg();
            var userId = HttpContext.Session.GetInt32("userid");
            var userName = HttpContext.Session.GetString("username");
            var realName = HttpContext.Session.GetString("realname");
            ViewData["Username"] = userName;
            ViewData["RealName"] = realName;
            if (userId == null)
            {
                msg.code = -1;
                msg.message = "尚未登录";
                return Redirect("/Auth/Login");
            }
            var shopDal = new ShopDal();
            var productDal = new ProductDal();
            var addrDal = new AddrDal();
            var product = productDal.GetProduct(productId);
            var shop = shopDal.GetShopById(product.ShopId);
            var addrs = addrDal.GetAddrByUserId((long)userId);
            List<Product> products = new List<Product>() { product };
            List<Shop> shops = new List<Shop>() { shop };
            Dictionary<string, string> productConfigs = new Dictionary<string, string>();
            ViewData["Products"] = products;
            ViewData["Shops"] = shops;
            ViewData["Addrs"] = addrs;
            ViewData["ProductConfigs"] = productConfigs;
            return View();
        }

        /// <summary>
        /// 确认下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Buy()
        {
            Msg msg = new Msg();
            var userId = HttpContext.Session.GetInt32("userid");
            var userName = HttpContext.Session.GetString("username");
            if (userId == null)
            {
                msg.code = -1;
                msg.message = "尚未登录";
                return Redirect("/Auth/Login");
            }
            var addr = Request.Form["addr"];
            var productIds = Request.Form["productId"].ToList();
            foreach (var productId in productIds)
            {

                var remark = Request.Form[$"textarea_{productId}"];
                var quantity = Request.Form[$"quantity_{productId}"];
                var productDal = new ProductDal();
                var product = productDal.GetProduct(long.Parse(productId));
                if (product != null)
                {
                    var pruchaseDal = new PurchaseDal();
                    var purchase = new Purchase();
                    purchase.ProductId = long.Parse(productId);
                    purchase.CustomerId = userId.Value;
                    purchase.BuyCount = int.Parse(quantity);
                    purchase.TotalPrice = product.PreferentialPrice * int.Parse(quantity);
                    purchase.LogisticsId = 0;//物流ID,下单时为空，商家发货后制定
                    purchase.Remark = remark;
                    purchase.Status = 0;
                    purchase.RecvAddr = addr;
                    purchase.CreateUser = userName;
                    purchase.CreateTime = DateTime.Now;
                    purchase.LastEditUser = userName;
                    purchase.LastEditTime = DateTime.Now;
                    int id = pruchaseDal.InsertT<Purchase>(purchase);
                    if (id > 0)
                    {
                        msg.code = 0;
                        msg.message = "成功";

                    }
                    else
                    {
                        msg.code = -1;
                        msg.message = "购买失败";
                        break;
                    }
                }
                else
                {
                    msg.code = -1;
                    msg.message = "商品不存在";
                    break;
                }
            }
            if (msg.code < 0)
            {
                ViewData["Msg"] = msg;
                return View();
            }
            else
            {
                return Redirect("/Purchase/Index");
            }

        }

        /// <summary>
        /// 从详情页面下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BuyWithForm()
        {
            Msg msg = new Msg();
            var userId = HttpContext.Session.GetInt32("userid");
            var userName = HttpContext.Session.GetString("username");
            if (userId == null)
            {
                msg.code = -1;
                msg.message = "尚未登录";
                return Json(msg);
            }
            var productId = long.Parse(Request.Form["productId"]);
            var quantity = int.Parse(Request.Form["quantity"]);
            var color = Request.Form["color"];
            var size = Request.Form["size"];
            var remark = $"颜色：{color},大小：{size}";
            var productDal = new ProductDal();
            var product = productDal.GetProduct(productId);
            var shopDal = new ShopDal();
            var addrDal = new AddrDal();
            var shop = shopDal.GetShopById(product.ShopId);
            var addrs = addrDal.GetAddrByUserId((long)userId);
            List<Product> products = new List<Product>() { product };
            List<Shop> shops = new List<Shop>() { shop };
            Dictionary<string, string> productConfigs = new Dictionary<string, string>();
            productConfigs.Add($"remark_{productId}", remark);
            productConfigs.Add($"quantity_{productId}", quantity.ToString());
            ViewData["Products"] = products;
            ViewData["Shops"] = shops;
            ViewData["Addrs"] = addrs;
            ViewData["ProductConfigs"] = productConfigs;
            return View("/Views/Purchase/Buy.cshtml");
        }

        /// <summary>
        /// 从购物车下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BuyWithCart()
        {
            Msg msg = new Msg();
            var userId = HttpContext.Session.GetInt32("userid");
            var userName = HttpContext.Session.GetString("username");
            if (userId == null)
            {
                msg.code = -1;
                msg.message = "尚未登录";
                return Json(msg);
            }
            var cartIds = Request.Form["chkCart"];
            if (string.IsNullOrEmpty(cartIds))
            {
                msg.code = -1;
                msg.message = "没有选择任何商品";
                return Json(msg);
            }
            var cartIdArr = cartIds.ToString().Split(',');

            if(cartIdArr!=null && cartIdArr.Length > 0)
            {
                var cartDal = new CartDal();
                var productDal = new ProductDal();
                var shopDal = new ShopDal();
                var addrDal = new AddrDal();
                List<Product> products = new List<Product>();
                List<Shop> shops = new List<Shop>();
                Dictionary<string, string> productConfigs = new Dictionary<string, string>();
                foreach (var cartId in cartIdArr)
                {
                    var cart = cartDal.GetCart(long.Parse( cartId));
                    var product = productDal.GetProduct(cart.ProductId);
                    if (product != null)
                    {
                        products.Add(product);
                    }
                    var shop = shopDal.GetShopById(product.ShopId);
                    if (shop != null)
                    {
                        shops.Add(shop);
                    }
                    
                    productConfigs.Add($"remark_{cart.ProductId}", cart.Remark);
                    productConfigs.Add($"quantity_{cart.ProductId}", cart.Quantity.ToString());
                }
                var addrs = addrDal.GetAddrByUserId((long)userId);
                ViewData["Products"] = products;
                ViewData["Shops"] = shops;
                ViewData["Addrs"] = addrs;
                ViewData["ProductConfigs"] = productConfigs;
                return View("/Views/Purchase/Buy.cshtml");
            }
            else
            {
                return View("/Views/Cart/Index");
            }
            
        }
    }
}
